#!/bin/sh
### BEGIN INIT INFO
# Provides: hp5370d
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Required-Start:
# Required-Stop:
# Short-Description: run hp5370 daemon
# Description: run hp5370 daemon
### END INIT INFO

HP5370D=hp5370d
HP5370D_EXEC=/usr/local/bin/$HP5370D
HP5370D_ARGS="-bg"
DEV=5370
#DEV=test
CAPE=cape-bone-${DEV}-00A0
DEV_PRU=${DEV}-P
PRU=cape-bone-${DEV_PRU}-00A0
SLOTS=`ls /sys/devices/bone_capemgr.*/slots`

[ -x $HP5370D_EXEC ] || exit 1

case "$1" in

  start)
    echo "Starting hp5370d"

	if test ! -e /lib/firmware/${CAPE}.dtbo -o /lib/firmware/${CAPE}.dts -nt /lib/firmware/${CAPE}.dtbo ; then
		echo compile ${DEV} device tree;
		dtc -O dtb -o /lib/firmware/${CAPE}.dtbo -b 0 -@ /lib/firmware/${CAPE}.dts;
# don't unload old slot because this is known to cause panics; must reboot
	fi

	if ! grep -q ${DEV} $SLOTS ; then
		echo load ${DEV} device tree;
		echo cape-bone-${DEV} > $SLOTS;
		sleep 2;
	fi

	if test ! -e /lib/firmware/${PRU}.dtbo -o /lib/firmware/${PRU}.dts -nt /lib/firmware/${PRU}.dtbo ; then
		echo compile ${DEV_PRU} device tree;
		(cd /lib/firmware; dtc -O dtb -o ${PRU}.dtbo -b 0 -@ ${PRU}.dts);
# don't unload old slot because this is known to cause panics; must reboot
	fi
	
	if ! grep -q ${DEV_PRU} $SLOTS ; then
		echo load ${DEV_PRU} device tree;
		echo cape-bone-${DEV_PRU} > $SLOTS;
	fi

# the test fixture is started separately by the Cloud9 IDE
	if [ $DEV != "test" ] ; then
		echo -n "Start hp5370d: "
		start-stop-daemon --start --background --exec $HP5370D_EXEC -- $HP5370D_ARGS
		RETVAL=$?
		if [ $RETVAL -eq 0 ] ; then
			echo "OK"
		else
			echo "FAIL"
		fi
	fi

    # have to do something here that returns zero status, otherwise systemd immediately stops us. Why?
    date
    ;;

  stop)
	if [ $DEV != "test" ] ; then
		echo -n "Stopping hp5370d: "
		start-stop-daemon --stop --name $HP5370D
		RETVAL=$?
		if [ $RETVAL -eq 0 ] ; then
			echo "OK"
		else
			echo "FAIL"
		fi
	fi
    ;;

  status)
    if [ -n "`/bin/pidof $HP5370D`" ] ; then
        echo "hp5370d is running."
    else
        echo "hp5370d is not running."
    fi
    ;;

  restart)
    $0 stop && sleep 1 && $0 start
    ;;

  *)
    echo "Usage: /etc/init.d/hp5370d {start|stop|status|restart}"
    exit 1

esac

exit 0
